<!-- 回款列表-新建回款信息组件  -->
<template>
  <a-modal
    width="80%"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
  >
    <template #title> 新建回款信息 </template>
    <div>
      <a-form :model="form" :rules="rules" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="returnedCode" label="回款编号：">
              <a-input
                size="large"
                placeholder="编号自动生成"
                v-model="form.info.collectionNumber"
                allow-clear
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="returnedType" label="回款类别：">
              <a-select
                placeholder="请选择回款类别"
                v-model="form.info.collectionTypeId"
              >
                <a-option
                  v-for="item in settingData"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="returnedWays" label="回款方式：">
              <a-input
                style="color: black"
                size="large"
                v-model="form.info.payMode"
                allow-clear
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="returnedTime" label="回款时间：">
              <a-date-picker
                show-time
                value-format="x"
                v-model="form.info.returnedTime"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="accountName" label="账号名称：">
              <a-cascader
                :field-names="fieldNames"
                :options="tableList.list"
                :style="{ width: '320px' }"
                v-model="form.info.collectionAccountId"
                @change="cgeAccount"
                placeholder="Please select ..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="account" label="账号：">
              <a-input
                placeholder="请填写账号"
                size="large"
                v-model="form.info.account"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="bank" label="开户行：">
              <a-input
                placeholder="请输入回款编号"
                size="large"
                v-model="form.info.bank"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="returnedMoney" label="回款金额：">
              <a-input-number
                :min="1"
                placeholder="请输入回款金额"
                :max="form.info.waitCollectionPrice"
                v-model="form.info.collectionPrice"
                :hide-button="true"
              >
                <template #prepend>￥</template>
                <template #append>
                  <a-select
                    :style="{ width: '120px' }"
                    placeholder="请选择单位"
                    v-model="form.info.collectionPriceUnit"
                  >
                    <a-option>人民币</a-option>
                    <a-option>港币</a-option>
                    <a-option>美金</a-option>
                  </a-select>
                </template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="contractMoney" label="总金额：">
              <a-input-number
                :min="1"
                placeholder="请输入合同总额"
                allow-clear
                v-model="form.info.totalPrice"
                disabled
                :hide-button="true"
              >
                <template #prepend>￥</template>
                <template #append> 人民币 </template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="AccuReturnedMoney" label="累计回款金额：">
              <a-input-number
                :min="1"
                placeholder="请输入累计回款金额"
                allow-clear
                v-model="form.info.accumulatedCollectionPrice"
                disabled
                :hide-button="true"
              >
                <template #prepend>￥</template>
                <template #append> 人民币 </template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="noReturnedMoney" label="未回款金额：">
              <a-input-number
                :min="1"
                placeholder="请输入未回款金额"
                v-model="form.info.waitCollectionPrice"
                disabled
                :hide-button="true"
              >
                <template #prepend>￥</template>
                <template #append> 人民币 </template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="file" label="凭证上传：">
              <a-space>
                <a-button type="primary" @click="upload">上传文件</a-button>
                <div v-if="isShow" class="uploadFile">
                  <span>{{ form.info.file[0].name }} </span>
                </div>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row> -->
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, computed, watchEffect, watch, ref } from 'vue';
  import { cloneDeep } from 'lodash';
  import { openChoiceFile } from '@/utils/file';
  import {
    GetAccountInfo,
    PostAccountInfo,
    DelAccountInfo,
    GetReceivableAccount,
  } from '@/api/order-management/returned-management/base-setting';
  import { GetReturnedTypeInfo } from '@/api/order-management/returned-management/base-setting';
  import { Message } from '@arco-design/web-vue';
  import { FileUpload } from '@/utils/upload';

  // 获取回款类型设置基本信息
  const settingData = ref();
  const getClientSettingInfo = async () => {
    const res = await GetReturnedTypeInfo();
    settingData.value = res;
  };

  getClientSettingInfo();
  const isShow = ref(false);
  let form = reactive<any>({
    info: {
      id: null,
      collectionTypeId: null,
      clientCompanyId: null,
      clientCompanyName: null,
      collectionNumber: '',
      collectionId: null,
      payMode: '',
      collectionAccountId: null,
      collectionTime: undefined,
      totalPrice: '',
      totalPriceUnit: '人民币',
      collectionProofFileId: undefined,
      createdAt: undefined,
      updatedAt: undefined,
      deletedAt: null,
      account: null,
      bank: '',
      collectionPrice: 0,
      collectionPriceUnit: '',
      waitCollectionPrice: '',
      waitCollectionPriceUnit: '人民币',
      receivablePrice: '',
      receivablePriceUnit: '人民币',
      accumulatedCollectionPrice: '',
      accumulatedCollectionPriceUnit: '人民币',
      file: [{ name: '', addr: '' }],
    },
  });

  // const formPriceData = reactive({});

  const formKey = Object.keys(form.info);
  const props = withDefaults(
    //参数说明
    defineProps<{
      visible: boolean;
      currForm: any;
      orderId: string;
    }>(),
    {
      visible: false,
    }
  );

  const emit = defineEmits(['update:visible', 'editReturnedEmit']);

  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  // let form = ref<any>({});

  // 储存账户数据
  const tableList = reactive<any>({
    list: [],
  });
  const fieldNames = {
    value: 'id',
    label: 'accountName',
    children: 'accountData',
  };
  // 获取账户数据
  const getData = async () => {
    try {
      const res = await GetAccountInfo({
        pageData: {
          page: 0,
          size: -1,
        },
      });
      let id = 1; // 后端的结构最外层没返回id，自己设置一个id
      res.forEach((item: any) => {
        id += 1;
        item.id = id;
        item.accountName = item.typeName;
        delete item.typeName;
      });
      tableList.list = JSON.parse(JSON.stringify(res));
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getData();

  const cgeAccount = async (id) => {
    const res = await GetReceivableAccount({ id });
    form.info.bank = res.AccountBank;
    form.info.account = res.AccountNumber;
  };

  watchEffect(() => {
    if (modalVisible.value) {
      console.log(props.currForm);

      let msg = {
        id: null,
        CollectionTypeId: null,
        clientCompanyId: null,
        clientCompanyName: null,
        collectionNumber: '',
        collectionId: null,
        payMode: '',
        collectionAccountId: null,
        collectionTime: undefined,
        totalPrice: '',
        totalPriceUnit: '人民币',
        collectionProofFileId: undefined,
        createdAt: undefined,
        updatedAt: undefined,
        deletedAt: null,
        account: null,
        bank: '',
        collectionPrice: 10000,
        collectionPriceUnit: '',
        waitCollectionPrice: '',
        waitCollectionPriceUnit: '人民币',
        receivablePrice: '',
        receivablePriceUnit: '人民币',
        accumulatedCollectionPrice: '',
        accumulatedCollectionPriceUnit: '人民币',
        file: [{ name: '', addr: '' }],
      };
      for (let i in props.currForm) {
        if (formKey.includes(i)) msg[i] = props.currForm[i];
      }
      form.info = msg;
      form.info.collectionPrice = 0;
      form.info.collectionNumber = '';
      form.info.returnedType = null;
      form.info.file = [{ name: '', addr: '' }];
      console.log(form.info);

      cgeAccount(form.info.collectionAccountId);
    }
  });

  const rules = reactive({});

  // 保存按钮
  const handleOk = () => {
    emit('editReturnedEmit', form.info);
    modalVisible.value = false;
  };

  // 取消按钮
  const handleCancel = () => {
    modalVisible.value = false;
  };

  const fileData = reactive<{ file?: File }>({});

  const upload = async () => {
    let file = new FormData();
    fileData.file = await openChoiceFile(
      ['.mp4', '.pdf', '.png', '.txt', '.jpg', 'docx'],
      1024 * 1024 * 10
    );
    file.append('data', fileData.file);
    const res: any = await FileUpload(file);
    if (res) {
      form.info.file[0].name = res.data.data.name;
      form.info.file[0].addr = res.data.data.sourceAddr;
      isShow.value = true;
    }
  };
</script>

<style scoped lang="less">
  .uploadFile {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    padding: 8px 10px 8px 12px;
    overflow: hidden;
    font-size: 14px;
    background-color: var(--color-fill-1);
    border-radius: var(--border-radius-small);
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    // margin-top: 10px;
  }
</style>
